<?php

class Model_Provider_Listener
{
    private static function api_model($order_sn)
    {
        if (!$order_sn) {
            throw new Exception('订单号为空');
        }
        $order = Model_Member_Order::order_info($order_sn);
        if (!$order) {
            throw new Exception('查询订单失败');
        }
        $api_model_res = Model_Provider_Api_Ticket_Order::get_api_model_by_order($order);
        if (!$api_model_res['status']) {
            throw new Exception($api_model_res['msg']);
        }
        $order['provider_product_id'] = $api_model_res['provider_product_id'];
        return [
            'provider_channel_order_model' => $api_model_res['provider_channel_order_model'],
            'ticket_api'                   => $api_model_res['ticket_api'],
            'order'                        => $order
        ];
    }

    public static function create($order_sn)
    {
        try {
            $data = self::api_model($order_sn);
            $provider_channel_order_model = $data['provider_channel_order_model'];
            return $provider_channel_order_model->create($data['order'], $data['ticket_api']);
        } catch (Exception $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }
    }

    public static function pay($order_sn)
    {
        try {
            $data = self::api_model($order_sn);
            $provider_channel_order_model = $data['provider_channel_order_model'];
            return $provider_channel_order_model->pay($data['order'], $data['ticket_api']);
        } catch (Exception $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }
    }

    public static function refund($order_sn)
    {
        try {
            $data = self::api_model($order_sn);
            $provider_channel_order_model = $data['provider_channel_order_model'];
            return $provider_channel_order_model->refund($data['order'], $data['ticket_api']);
        } catch (Exception $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }
    }

    public static function cancel($order_sn)
    {
        try {
            $data = self::api_model($order_sn);
            $provider_channel_order_model = $data['provider_channel_order_model'];
            return $provider_channel_order_model->cancel($data['order'], $data['ticket_api']);
        } catch (Exception $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }
    }
}